package protocol;

import java.net.SocketException;
import java.util.Random;

import udpSocket.layerOneServer;

public class layerTwoServer {

	public static void main(String args[]) throws Exception{
		
		String packet = "";
		String oldPacket = "1";
		String sequenceNumber = "";
		
		boolean receivedPacket = false;

		layerOneServer physical = new layerOneServer();

		while(true){
			while(receivedPacket==false){
				try{
				packet = physical.serverReceive();
				}catch(SocketException e){
					e.printStackTrace();
				}
				if(packet!="")
					receivedPacket = true;
			}
			
			System.out.println(packet);
			System.out.println("Package received: "+packet.substring(1, packet.length()-1));
			System.out.println("Current sequence number received: "+packet.charAt(0));
			System.out.println("Previous sequence number received: "+oldPacket.charAt(0));

			if(oldPacket!=packet)
				oldPacket = packet;
			else
				System.out.println("Same sequence number: Discarding package!");

			sequenceNumber = ""+packet.charAt(0);
			
			System.out.println(sequenceNumber);

			if(sequenceNumber.equals("0"))
				sequenceNumber = "1";
			else
				sequenceNumber = "0";
			
			System.out.println("Sequence Number sent: "+sequenceNumber);

			if(noise()==false)
				physical.serverSend(sequenceNumber);
			
			receivedPacket = false;
		}
	}
	
	public static boolean noise(){
		Random prob = new Random();
		boolean noise=false;
		int num = prob.nextInt(10);

		if(num==5){
			noise = true;
		}

		return noise;
	}

}
